package com.ict.web.controller.yzq;

import com.ict.common.annotation.Log;
import com.ict.common.core.controller.BaseController;
import com.ict.common.core.domain.AjaxResult;
import com.ict.common.core.page.TableDataInfo;
import com.ict.common.enums.BusinessType;
import com.ict.web.mapper.PerformanceIndicatorsMapper;
import com.ict.web.service.IScoreService;
import com.ict.web.utils.pdf.PdfUtil;
import com.ict.web.dto.QueryPerformanceStatisticsDto;
import com.ict.web.service.IProjectManagementService;
import com.ict.web.vo.PerIndectorsDetailsVo;
import com.ict.web.vo.PerformanceStatisticsListVo;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 绩效统计Controller
 *
 * @author xss
 * @date 2022-03-11
 */
@RestController
@RequestMapping("/web/performanceStatistics")
@Api(tags = "绩效统计")
public class PerformanceStatisticsController extends BaseController {

    @Autowired
    private IProjectManagementService projectManagementService;
    @Autowired
    private IScoreService scoreService;
    @Autowired
    private PerformanceIndicatorsMapper performanceIndicatorsMapper;

    @ApiOperation(value = "绩效统计列表")
    @GetMapping("/statisticsList")
    public TableDataInfo statisticsList(QueryPerformanceStatisticsDto queryDto) {
        startPage();
        List<PerformanceStatisticsListVo> list = projectManagementService.performanceStatisticsList(queryDto);
        return getDataTable(list);
    }

    @ApiOperation(value = "绩效统计详情")
    @GetMapping("getInfo/{proId}")
    public AjaxResult getInfo(@PathVariable Long proId) {
        return AjaxResult.success(projectManagementService.selectPerformanceStatisticsByIdProId(proId));
    }

    @ApiOperation("导出绩效统计")
    @Log(title = "绩效统计列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody QueryPerformanceStatisticsDto queryDto) throws UnsupportedEncodingException {

        String fileName = "绩效统计.pdf";
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

//        QueryPerformanceStatisticsDto queryDto = new QueryPerformanceStatisticsDto();
//        queryDto.setProjectIds(projectIds);
        List<PerformanceStatisticsListVo> list = projectManagementService.performanceStatisticsList(queryDto);

        List<Long> perIds = list.stream().map(s -> s.getPerId()).collect(Collectors.toList());

        List<List<PerIndectorsDetailsVo>> lists = new ArrayList<>();
        perIds.forEach(s -> {
            List<PerIndectorsDetailsVo> perIndectorsDetailsVos = performanceIndicatorsMapper.selectPerformanceIndicatorsDetail(s);
            lists.add(perIndectorsDetailsVos);
        });

        List<Long> projectIds = list.stream().map(s -> s.getProjectId()).collect(Collectors.toList());

        BigDecimal decimal = scoreService.selectAverageScore(projectIds);

        Document document = new Document();
        PdfWriter writer = null;
        try {
            // 创建输出流
            ServletOutputStream outputStream = response.getOutputStream();
            writer = PdfWriter.getInstance(document, outputStream);
            document.open();
            // 绩效统计概览表
            document.add(PdfUtil.getParagraph("\n· 绩效统计概览表\n\n", PdfUtil.BLOCK_FONT, -1));
            PdfPTable dataTable = PdfUtil.setPdfTable(list);
            document.add(dataTable);
            document.add(PdfUtil.getParagraph("\n平均分：" + decimal.toString(), PdfUtil.INFO_FONT, -1));

            //详情指标
            for (int i = 0; i < list.size(); i++) {
                document.add(PdfUtil.getParagraph("\n· 项目绩效详情\n\n", PdfUtil.BLOCK_FONT, -1));

                PdfUtil.createInformation(document, list.get(i));

                document.add(PdfUtil.getParagraph("\n· 绩效统计\n\n", PdfUtil.BLOCK_FONT, -1));
                document.add(PdfUtil.setDetailTable(lists.get(i)));
            }

            document.newPage();
        } catch (Exception e) {
            logger.error("绩效下载失败！+" + e.getMessage());
            e.printStackTrace();
        } finally {
            document.close();
            writer.close();
        }

    }
}
